package com.jc.oms.controller.jg;

import com.alibaba.fastjson.JSONObject;
import com.jc.cds.model.CustomSupplierProduct;
import com.jc.common.util.Base64Util;
import com.jc.common.util.WebUtils;
import com.jc.ds.model.SupplierProduct;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.JgApi;
import com.jc.framework.enums.LogType;
import com.jc.oms.controller.BaseController;
import com.jc.service.h5.ShopService;
import com.jc.service.jg.JgService;
import com.jc.service.jgservice.JgHttpService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.systemloglist.SystemLogListService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@Controller
@RequestMapping("jgProduct")
public class JgProductController extends BaseController{

    @Autowired
    private JgHttpService jgHttpService;
    @Autowired
    private SupplierProductService supplierProductService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private JgService jgService;
    @Autowired
    private SystemLogListService systemLogListService;

    @RequestMapping(value = "/jgProductNumber",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> jgProductNumber(){
        Map<String,Object> resultMap = new HashMap<>();
        try{
            Integer limit = 100;
            Integer start = 0;
            while (true){
                Integer finalStart = start;
                List<CustomSupplierProduct> customSupplierProducts = supplierProductService.selectProductByLimitOrSupplierName(new HashMap<String, Object>() {{
                    put("supplierName","吉贡电商");
                    put("limit",limit);
                    put("start", finalStart);
                }});
                //查询不到sku 结束循环
                if(CollectionUtils.isEmpty(customSupplierProducts)){
                    break;
                }
                //遍历 取出skuId集合
                List<Long> ids = new ArrayList<>();
                customSupplierProducts.forEach(customSupplierProduct -> {
                    ids.add(Long.valueOf(customSupplierProduct.getProductId()));
                });
                Map<String,Object> param = new HashMap<>();
                param.put("productIds",ids);
                JSONObject jsonObject = jgHttpService.httpJgUtil(JgApi.PRODUCT_NUMBER_SELECT.getName(),param, LogType.JG_PRODUCT_NUMBER);
                //获取数据
                List<Map<String,Object>> data = JSONObject.parseObject(jsonObject.get("data").toString(), List.class);
                data.forEach(pro->{
                    String productId = pro.get("productId").toString();
                    //根据第三方商品id查询
//                    List<CustomSupplierProduct> customSupplierProductsList2 = supplierProductService.selectProductByLimitOrSupplierName(new HashMap<String, Object>() {{
//                        put("start", 0);
//                        put("limit", 1);
//                        put("supplierName", "吉贡电商");
//                        put("productId", productId);
//                    }});
//                    supplierProductService.modify(new SupplierProduct(){{
//                        setId(customSupplierProductsList2.get(0).getId());
//                        setInventoryNum(99999);
//                    }},false);
                    List<CustomSupplierProduct> customSupplierProductsList = supplierProductService.selectProductByLimitOrSupplierName(new HashMap<String, Object>() {{
                        put("start", 0);
                        put("limit", 1);
                        put("supplierName", "吉贡电商");
                        put("productId", productId);
                    }});
                    if (CollectionUtils.isEmpty(customSupplierProductsList)){
                        System.out.println("=====产品skuId"+productId);
                        return;
                    }
                    SupplierProduct supplierProduct = customSupplierProductsList.get(0);
                    String shopNum = supplierProduct.getInventoryNum().toString();//商城库存
                    String jgNum;//吉贡库存
                    if (supplierProduct.getHastax() ==0){
                        //不含税
                        jgNum = pro.get("noTaxNum").toString();
                    }else{
                        //含税
                        jgNum = pro.get("taxNum").toString();
                    }
                    //不相等 修改库存
                    if(!shopNum.equals(jgNum)){
                    	getLoger().error("修改产品库存并推送----------------> {},库存:{} ", productId, jgNum);
                        supplierProductService.modify(new SupplierProduct(){{
                            setId(supplierProduct.getId());
                            setInventoryNum(Integer.valueOf(jgNum));
                        }},false);
                        shopService.pushInventory(supplierProduct.getId(),jgNum);
                    }
                });
                start = start + limit;
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("code",99999);
            resultMap.put("message",e.getLocalizedMessage());
        }
        return resultMap;
    }

    
    
    @RequestMapping(value = "/jgProductNumberallzero",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> jgProductNumberAllZreo(){

        Map<String,Object> resultMap = new HashMap<>();
        int pageIndex = 0;
        try{
            Integer limit = 100;
            Integer start = 0;
            while (true){
            	pageIndex++;
                Integer finalStart = start;
                List<CustomSupplierProduct> customSupplierProducts = supplierProductService.selectProductByLimitOrSupplierName(new HashMap<String, Object>() {{
                    put("supplierName","吉贡电商");
                    put("limit",limit);
                    put("start", finalStart);
                }});
                //查询不到sku 结束循环
                if(CollectionUtils.isEmpty(customSupplierProducts)){
                	getLoger().error("查不到数据,推出循环==================================================================");
                    break;
                }
                //遍历 取出skuId集合
                List<Long> ids = new ArrayList<>();
                customSupplierProducts.forEach(customSupplierProduct -> {
                    ids.add(Long.valueOf(customSupplierProduct.getProductId()));
                });
                Map<String,Object> param = new HashMap<>();
                param.put("productIds",ids);
                JSONObject jsonObject = jgHttpService.httpJgUtil(JgApi.PRODUCT_NUMBER_SELECT.getName(),param, LogType.JG_PRODUCT_NUMBER);
                //获取数据
                List<Map<String,Object>> data = JSONObject.parseObject(jsonObject.get("data").toString(), List.class);
                List<Long> returnList = new ArrayList<Long>();
                data.forEach(pro->{
                    String productId = pro.get("productId").toString();
                    List<CustomSupplierProduct> customSupplierProductsList = supplierProductService.selectProductByLimitOrSupplierName(new HashMap<String, Object>() {{
                        put("start", 0);
                        put("limit", 1);
                        put("supplierName", "吉贡电商");
                        put("productId", productId);
                    }});
                    if (CollectionUtils.isEmpty(customSupplierProductsList)){
                        getLoger().error(productId + "当前产品查不到数据, 进入下一个产品的查询推送............................");
                        return;
                    }
                    SupplierProduct supplierProduct = customSupplierProductsList.get(0);
                    String shopNum = supplierProduct.getInventoryNum().toString();//商城库存
                    String jgNum;//吉贡库存
                    
                    String hasTax = pro.get("hasTax") == null ? "0" : pro.get("hasTax").toString();
                    
                    
                    if (Integer.parseInt(hasTax) == 0){
                        //不含税
                        jgNum = pro.get("noTaxNum").toString();
                    }else{
                        //含税
                        jgNum = pro.get("taxNum").toString();
                    }
                    
                    //不相等 修改库存
                    if(!shopNum.equals(jgNum)){
                    	getLoger().error("修改产品库存并推送-------------------------------> {},库存:{} ", productId, jgNum);
                        supplierProductService.modify(new SupplierProduct(){{
                        	setHastax(Integer.parseInt(hasTax));
                            setId(supplierProduct.getId());
                            setInventoryNum(Integer.valueOf(jgNum));
                        }},false);
                        shopService.pushInventory(supplierProduct.getId(),jgNum);
                    }else {
                    	getLoger().error("{}这个产品 系统库存 {} , 吉贡库存 {}  因为库存相等，不推送", productId, shopNum,jgNum);
                    }
                    
                    returnList.add(Long.valueOf(productId));
                });
                
                
                for(int k = 0 ; ids != null && k < ids.size() ; k++) {
                	
                	Long pid = ids.get(k);
                	if(!returnList.contains(pid)) {//吉贡无库存
                		List<CustomSupplierProduct> customSupplierProductsList = supplierProductService.selectProductByLimitOrSupplierName(new HashMap<String, Object>() {{
                            put("start", 0);
                            put("limit", 1);
                            put("supplierName", "吉贡电商");
                            put("productId", pid);
                        }});
                		if(CollectionUtils.isEmpty(customSupplierProductsList)) {
                			break;
                		}
                		
                		SupplierProduct sp  = customSupplierProductsList.get(0);
                		supplierProductService.modify(new SupplierProduct(){{
                            setId(sp.getId());
                            setInventoryNum(Integer.valueOf(0));
                        }},false);
                        shopService.pushInventory(sp.getId(),"0");
                        getLoger().error("==修改产品库存并推送-------------------------------> {},库存:{} ", pid, 0);
                		
                	}
                	
                }
                
                
                
                
                getLoger().error("当前已经处理完成第" + pageIndex + " 页   " + param == null ? "0" : param.size()  +  "   ||    " + data == null ? "0" : data.size() + "  条的商品库存推送========================");
                if(param != null && data != null) {
                	if(param.size() != data.size()) {
                		
                		getLoger().error("***吉贡数据出现问题,  反馈库存数量错误 : ");
                		getLoger().error("***请求  :  " + ids.toString());
                		getLoger().error("***吉贡数据出现问题,  反馈库存数量错误 : " + JSONObject.toJSONString(data));
                	}
                }
                start = start + limit;
                
            }
        }catch (Exception e){
        	getLoger().error("批量更新库存发生错误,停止更新 错误信息: {}, {}", e.getMessage(), e);
            resultMap.put("code",99999);
            resultMap.put("message",e.getLocalizedMessage());
        }
        return resultMap;
    
    }
    
    
    

    //回调产品库存
    @RequestMapping(value = "/callBackProductNumber",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> callBackProductNumber(HttpServletRequest request){
        Map<String,Object> resultMap = new HashMap<>();
        try{
            Map<String, Object> requestParam = WebUtils.ReadAsChars(request);
            systemLogListService.addSystemLog(JSONObject.toJSONString(requestParam), Conclusion.OK,"",LogType.JG_PRO_NUMBER_CALLBACK,"");
            Map<String,Object> map = JSONObject.parseObject(Base64Util.decode(requestParam.get("data").toString()), Map.class);
            if ("104".equals(map.get("mainType").toString())){
                jgService.updateProNum(Long.valueOf(map.get("goodsId").toString()));
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("code",99999);
            resultMap.put("message",e.getLocalizedMessage());
        }
        return resultMap;
    }



}

